package com.czh.dao.Bill;

import com.czh.dao.BaseDao;
import com.czh.pojo.Bill;
import com.mysql.cj.util.StringUtils;
import org.apache.commons.pool.BaseObjectPool;
import org.junit.jupiter.api.Test;

import javax.annotation.Resource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class BillDaoImpl implements BillDao{
    @Override
    public List<Bill> BillList(Connection con, String productName, int providerId, int isPayment) {
        PreparedStatement pre = null;
        ResultSet res = null;
        StringBuffer sql = new StringBuffer("select b.*,a.proName from smbms_provider a,smbms_bill b " +
                "where a.id=b.providerId");
        List<Bill> billList = new ArrayList<>();
        if(con!=null){
            List<String> params = new ArrayList<>();
            if(!StringUtils.isNullOrEmpty(productName)){
                sql.append("  and b.productName like ?");
                params.add("%"+productName+"%");
            }
            if(providerId!=0){
                sql.append("  and b.providerId =?");
                params.add(String.valueOf(providerId));
            }
            if(isPayment!=0){
                sql.append("  and b.isPayment =?");
                params.add(String.valueOf(isPayment));
            }
            sql.append(" order by b.creationDate desc ");
            try {
                res = BaseDao.getSelect(con, pre, res, sql.toString(), params.toArray());
                while (res.next()){
                    Bill bill = new Bill();
                    bill.setId(res.getInt("id"));
                    bill.setBillCode(res.getString("billCode"));
                    bill.setProductName(res.getString("productName"));
                    bill.setProductDesc(res.getString("productDesc"));
                    bill.setProductUnit(res.getString("productUnit"));
                    bill.setProductCount(res.getBigDecimal("productCount"));
                    bill.setTotalPrice(res.getBigDecimal("totalPrice"));
                    bill.setIsPayment(res.getInt("isPayment"));
                    bill.setProviderId(res.getInt("providerId"));
                    bill.setProviderName(res.getString("proName"));
                    bill.setCreationDate(res.getTimestamp("creationDate"));
                    bill.setCreatedBy(res.getInt("createdBy"));
                    billList.add(bill);
                }
                BaseDao.closeConnect(null,pre,res);
            } catch (SQLException e) {
                throw new RuntimeException("Dao层BillList出错!");
            }
        }
        return billList;
    }
}
